package tingshu.servlet.track;

import com.fasterxml.jackson.databind.ObjectMapper;
import tingshu.repository.TrackRepo;
import tingshu.util.Log;
import tingshu.view_object.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author houdaiqin
 * @date 2022/07/16 22:22
 **/
@WebServlet("/studio/track/record.json")
public class RecordJsonServlet extends HttpServlet {
    private final ObjectMapper objectMapper=new ObjectMapper();
    private final TrackRepo trackRepo=new TrackRepo();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String title = req.getParameter("title");
        if(title==null || title.equals("")){
            throw new ServletException("音频名称为空");
        }
        String type = req.getHeader("Content-Type");
        if (type==null||type.equals("")){
            throw new ServletException("音频为空");
        }
        Log.println("title"+title);
        Log.println("type"+type);

        UserVO currentUser=null;
        HttpSession session=req.getSession(false);
        if (session!=null){
            currentUser=(UserVO) session.getAttribute("currentUser");
        }

        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        PrintWriter writer= resp.getWriter();
        if (currentUser==null){
            Log.println("用户未登录");
            HashMap<String,Boolean> result=new HashMap<>();
            result.put("result",false);
            String json=objectMapper.writeValueAsString(result);
            Log.println(json);
            writer.println(json);
            return;
        }else{
            trackRepo.insert(currentUser.uid,title,type, req.getInputStream());
            Log.println("将数据保存到数据库中");
            HashMap<String,Boolean> result=new HashMap<>();
            result.put("result",false);
            String json=objectMapper.writeValueAsString(result);
            Log.println(json);
            writer.println(json);
        }
    }
}